unit uTrackInterface;

interface

uses uBusDriver;

type

  TTrackInterface = class
  private
    aBusDriver: TBusDriver;


  protected
    procedure CreateBusDriver; virtual;
    property BusDriver: TBusDriver read aBusDriver write aBusDriver;

  public
    constructor Create;
    destructor  Destroy; override;

    function  Connect: boolean;
    procedure Disconnect;

    function  IsSegmentOccupied(paSegmentAddress: Integer): boolean;
    procedure GetSegmentOccupations(paSegments: array of Integer; var paResults: array of Integer);

  end;

implementation

uses SysUtils, uBusMessage;

{ TTrackInterface }

function TTrackInterface.Connect: boolean;
begin
  if aBusDriver = nil then
    CreateBusDriver;

  result := aBusDriver.Connect;
end;

constructor TTrackInterface.Create;
begin
  aBusDriver := nil;
end;

procedure TTrackInterface.CreateBusDriver;
begin
  raise Exception.Create('Method CreateBusDriver() is not implemented.');
end;

destructor TTrackInterface.Destroy;
begin
  Disconnect;
  if aBusDriver<>nil then
    aBusDriver.Destroy;
  inherited;
end;

procedure TTrackInterface.Disconnect;
begin
  if aBusDriver<>nil then
    if aBusDriver.IsConnected then
      aBusDriver.Disconnect;
end;

procedure TTrackInterface.GetSegmentOccupations(paSegments: array of Integer; var paResults: array of Integer);
var
  msg: TBusMessage;
  len, i: Cardinal;
begin
  if (aBusDriver = nil) or not (aBusDriver.IsConnected) then
  begin
    // aSegmentOccupied := true;
    exit;
  end;

  len := Length(paSegments);
  msg.length := len + 2;

  msg.data[0] := $03;
  msg.data[1] := len;

  for i := 0 to len - 1 do
    msg.data[i+2] := paSegments[i];

  if aBusDriver.SendMessageAndGetAnswer(msg) then
  begin
    for i := 0 to msg.data[1] - 1 do
      paResults[i] := msg.data[i+2];
  end;
  //else
    //aSegmentOccupied := true;
end;

function TTrackInterface.IsSegmentOccupied(paSegmentAddress: Integer): boolean;
var
  seg, res: array[0..0] of Integer;
begin
  seg[0] := paSegmentAddress;
  GetSegmentOccupations(seg, res);
  result := (res[0] <> 0);
end;

end.
